package org.dong.control;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.dong.Tool.ApplicationUtil;
import org.dong.pojo.*;
import org.dong.pojo.qo.ReportQo;
import org.dong.service.OrderService;
import org.dong.service.ProjectService;
import org.dong.service.ReportService;
import org.dong.service.TargetService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ReportControl {


    @Resource
    OrderService orderService;
    @Resource
    ReportService reportService;
    @Resource
    TargetService targetService;


    @PostMapping("/Report/addReport")
    public Dto addReport(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Dto dto = new Dto();
        AdminUser user= (AdminUser) req.getSession().getAttribute("user");

        String orderSn = req.getParameter("orderSn");

        //先判断订单是否存在
        Order order = orderService.getOrderInfo(null, orderSn);

        if (order != null) {
            //查询对应订单的对应科室是否已经已经核销
            Report reportInfo = reportService.getReportInfo(null, order.getId(), user.getSubjectId(),null);

            if (reportInfo == null) {
                //查询订单是否有本科室的体检项目
                List<Project> projects = ApplicationUtil.getContext().getBean(ProjectService.class).getMealProject(order.getMealId(), user.getSubjectId());
                if (projects != null) {
                    for (Project project : projects) {
//                          System.out.println("pppppp"+project);
                        //开始生成报告
                        Report report = new Report();
                        report.setUserId(order.getUserId());
                        report.setOrderId(order.getId());
                        report.setProjectId(project.getId());
                        report.setProjectName(project.getProjectName());
                        report.setDoctorId(user.getId());
                        report.setSubjectId(user.getSubjectId());
                        report.setDoctorName(user.getAdminName());
                        report.setCreateTime(BigDecimal.valueOf(System.currentTimeMillis()));

                        final Integer integer = reportService.addReport(report);
                        if (integer > 0) {
                            //生成报告详情
                            List<Target> targets = targetService.getTargetList(project.getId());
                            for (Target target : targets) {
                                targetService.addTargetDetail(target.getId(), report.getId());
                            }

                            dto.setErrMsg("核销成功，请开始体检");
                            dto.setLocation("meal_list");
                            dto.setStatusCode(200);
                        }
                    }

                } else {
                    dto.setErrMsg("该导检单并没有本科室的检查项目");
                    dto.setStatusCode(2001);
                }
            } else {
                dto.setErrMsg("导检单在本科室已经核销，请勿重复核销");
                dto.setStatusCode(2001);
            }
        } else {
            dto.setErrMsg("导检单不存在");
            dto.setStatusCode(2001);
        }


        return dto;


    }

    @PostMapping("/Report/getReportList")
    public Dto getReportList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Dto dto = new Dto();
        AdminUser user = (AdminUser) req.getSession().getAttribute("user");

        String sDate = req.getParameter("sdate");
        String eDate = req.getParameter("edate");
        String sName = req.getParameter("sname");
        String sProject = req.getParameter("sproject");
        int page = Integer.parseInt(req.getParameter("page")) -1;


        if (page < 0) {
            page = 0;
        } else {
            page = page * 5;
        }

        List<Report> reportList = reportService.getReportList(page, user.getId(), sDate, eDate, sName, sProject);
        Integer reportListCount = reportService.getReportListCount(user.getId(), sDate, eDate, sName, sProject);
        if (reportList != null) {

            Map<String, Object> datas = new HashMap<String, Object>();
            datas.put("order", reportList);
            datas.put("count", reportListCount);
            dto.setDatas(datas);
            dto.setErrMsg("体检列表");
            dto.setStatusCode(200);
        } else {
            dto.setErrMsg("没有数据");
            dto.setStatusCode(200);
        }

        return dto;


    }

    @PostMapping("/Report/getReportInfo")
    public Dto getReportInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Dto dto = new Dto();

        int id = Integer.parseInt(req.getParameter("id"));

        //先查询体检订单是否存在
        final Report report = reportService.getReportInfo(id, null, null,null);
        if (report != null) {
            //查询对应的订单细项
            List<Target> details = targetService.getDetailList(report.getId());

            if (details != null) {
                ReportQo reportQo = new ReportQo();
                reportQo.setId(report.getId());
                reportQo.setProjectName(report.getProjectName());
                reportQo.setSubjectContent(report.getSubjectContent());
                reportQo.setTargets(details);


                Map<String, Object> datas = new HashMap<String, Object>();
                datas.put("info", reportQo);
                dto.setDatas(datas);
                dto.setErrMsg("详细信息");
                dto.setStatusCode(200);

            } else {
                dto.setErrMsg("没有细项");
                dto.setStatusCode(2001);
            }
        } else {
            dto.setErrMsg("体检订单不存在");
            dto.setStatusCode(2001);
        }


        return dto;

    }

    @PostMapping("/Report/updateReportInfo")
    public Dto updateReportInfo(HttpServletRequest req, HttpServletResponse resp){
        Dto dto = new Dto();

        String data = req.getParameter("data");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> dataMap = objectMapper.readValue(data, Map.class);
            //更新细项参数
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String key = entry.getKey();
                if(!key.equals("id") && !key.equals("project") && !key.equals("status") &&!key.equals("content")){

                    String value = entry.getValue();
                    if(value != null && !value.equals("")){

                        Integer integer = targetService.updateTargetInfo(Integer.valueOf(key), value);
                    }

                }
            }
            //更新报告内容
            //1获取参数
            int id = Integer.parseInt(dataMap.get("id"));
            int status = Integer.parseInt(dataMap.get("status"));
            String content = dataMap.get("content");
            //更新报告状态
            Integer i = reportService.updateReportInfo(id, status, content);
            if(i > 0){
                dto.setStatusCode(200);
                dto.setErrMsg("更新成功");
            }else{
                dto.setStatusCode(2002);
                dto.setErrMsg("更新失败");

            }


        } catch (Exception e) {
            e.printStackTrace();
        }



        return dto;
    }

}
